package com.bit.talkoftoday;

import java.io.InputStream;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.bit.talkoftoday.ShakeActivity.ImageCreate;

import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.os.Vibrator;
import android.util.Log;
import android.widget.Toast;

public class BlogSub extends BroadcastReceiver{
	public Context context;
	private String bookName;
	private String contents;
	private Vibrator vibrator;
	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		this.context = context;
		int a= intent.getIntExtra("request_code", 0);
		Log.v("dd", a+"==bolgsub");
		if(a == 0){
			Intent intent3 = new Intent(context,MainActivity_2.class);
			intent3.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startActivity(intent3);
		}
		else if(a == 1){
			readX();
			ImageCreate i = new ImageCreate();
			i.start();
			vibrator = (Vibrator)context.getSystemService(context.VIBRATOR_SERVICE);
			vibrator.vibrate(2000);
		}
	}
	class ImageCreate extends Thread{
		@Override
		public void run() {
			try {
				sleep(1000);
				Intent intent = new Intent(context,CardActivity.class);
				intent.putExtra("bookName", bookName);
				intent.putExtra("contents", contents);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				context.startActivity(intent);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	public void readX(){
		HSSFWorkbook wb;
		HSSFSheet sheet;
		HSSFRow row;
		try{
			InputStream fis=context.getResources().getAssets().open("SelectData.xls");
			wb=new HSSFWorkbook(fis);
			fis.close();
			sheet=wb.getSheetAt(0);
			if(wb!=null&&sheet!=null){
				int srow=sheet.getFirstRowNum()+1;
				int erow=sheet.getLastRowNum();
				row=sheet.getRow(0);
				int scol=row.getFirstCellNum();
				int ecol=row.getLastCellNum();
				int random=(int)(Math.random()*(erow-srow+1))+srow;
				HSSFRow tmp;
				HSSFCell cell;
				tmp= sheet.getRow(random);
				for(int i=scol; i<ecol; i++){
					cell= tmp.getCell(i);
					if(i==scol){
						bookName=cell.getStringCellValue();
					}else{
						contents=cell.getStringCellValue();
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
